package com.scm.service.impl;

import java.util.List;

import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.exception.ServiceException;
import com.scm.common.utils.TOTransferHelper;
import com.scm.dto.req.inventory.SaveScmInventoryInReq;
import com.scm.dto.resp.invent.QueryInventoryInPageResp;
import com.scm.dto.resp.invent.ScmInventoryInDetailDo;
import com.scm.dto.resp.product.ScmProductDo;
import com.scm.persist.model.ScmInventoryIn;
import com.scm.persist.model.ScmInventoryInDetail;
import com.scm.persist.model.ScmInventoryInDetailExample;
import com.scm.persist.model.ScmInventoryInExample;
import com.scm.persist.mybatis.ScmInventoryInDetailMapper;
import com.scm.persist.mybatis.ScmInventoryInMapper;
import com.scm.service.IScmInventoryInService;
import com.scm.service.IScmInventoryStashProductService;
import org.apache.commons.compress.utils.Lists;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 库存-入库信息Service业务层处理
 * 
 * @author reptilemanager
 * @date 2024-03-17
 */
@Service
public class ScmInventoryInServiceImpl implements IScmInventoryInService
{
    @Autowired
    private ScmInventoryInMapper scmInventoryInMapper;

    @Autowired
    private ScmInventoryInDetailMapper scmInventoryInDetailMapper;

    @Autowired
    private IScmInventoryStashProductService inventoryStashProductService;

    @Autowired
    private ScmProductServiceImpl scmProductServiceImpl;


    /**
     * 查询库存-入库信息
     * 
     * @param id 库存-入库信息主键
     * @return 库存-入库信息
     */
    @Override
    public ScmInventoryIn selectScmInventoryInById(Long id)
    {
        return scmInventoryInMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询库存-入库信息列表
     * 
     * @param scmInventoryIn 库存-入库信息
     * @return 库存-入库信息
     */
    @Override
    public QueryInventoryInPageResp selectScmInventoryInList(ScmInventoryIn scmInventoryIn , Integer start, Integer size)
    {
        ScmInventoryInExample example = new ScmInventoryInExample();

        int count = scmInventoryInMapper.countByExample(example);
        List<ScmInventoryIn> list = Lists.newArrayList();
        if(count>0){

            RowBounds rowBounds = new RowBounds(start,size);

            list =  scmInventoryInMapper.selectByExampleWithRowbounds(example,rowBounds);
        }
        return QueryInventoryInPageResp.builder().total(count).list(list).build();
    }

    /**
     * 新增库存-入库信息
     * 
     * @param scmInventoryIn 库存-入库信息
     * @return 结果
     */
    @Override
    public int insertScmInventoryIn(ScmInventoryIn scmInventoryIn)
    {
        return 1;
    }

    /**
     * 修改库存-入库信息
     * 
     * @param scmInventoryIn 库存-入库信息
     * @return 结果
     */
    @Override
    public int updateScmInventoryIn(ScmInventoryIn scmInventoryIn)
    {
        return scmInventoryInMapper.updateByPrimaryKeySelective(scmInventoryIn);
    }

    /**
     * 批量删除库存-入库信息
     * 
     * @param id 需要删除的库存-入库信息主键
     * @return 结果
     */
    @Override
    public int deleteScmInventoryInById(String id)
    {
        ScmInventoryIn scmInventoryIn = this.selectScmInventoryInById(Long.valueOf(id));

        if("beInStorage".equals(scmInventoryIn.getStatus())){
            throw new ServiceException("已入库单据不能删除！");
        }
        scmInventoryIn.setStatus("del");
        this.updateScmInventoryIn(scmInventoryIn);
        return 1;
    }

    /**
     * 删除库存-入库信息信息
     * 
     * @param id 库存-入库信息主键
     * @return 结果
     */
    @Override
    public int deleteScmInventoryInById(Long id)
    {
        return scmInventoryInMapper.deleteByPrimaryKey(id);
    }


    @Override
    public List<ScmInventoryInDetailDo> selectScmInventoryInDetailListList(Long inventoryInId) {

        ScmInventoryInDetailExample example = new ScmInventoryInDetailExample();
        example.createCriteria().andInventoryInIdEqualTo(inventoryInId);
        List<ScmInventoryInDetail> list = scmInventoryInDetailMapper.selectByExample(example);

        List<ScmInventoryInDetailDo> result = Lists.newArrayList();
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)){

            list.forEach(scmInventoryInDetail -> {

                ScmInventoryInDetailDo inventoryInDetailDo = TOTransferHelper.trans2TO(scmInventoryInDetail,ScmInventoryInDetailDo.class);

                ScmProductDo scmProductDo = scmProductServiceImpl.selectScmProductById(scmInventoryInDetail.getTenantId(),scmInventoryInDetail.getProductId());

                if(scmProductDo!=null){
                    inventoryInDetailDo.setBrand(scmProductDo.getBrand());
                    inventoryInDetailDo.setProductCode(scmProductDo.getProductCode());
                    inventoryInDetailDo.setProductName(scmProductDo.getProductName());
                    inventoryInDetailDo.setProductUnit(scmProductDo.getProductUnit());
                    inventoryInDetailDo.setSource(scmProductDo.getSource());
                }
                result.add(inventoryInDetailDo);
            });
        }

        return result;
    }

    @Override
    public int saveScmInventoryIn(SaveScmInventoryInReq req, SysUser sysUser) {


        ScmInventoryIn scmInventoryIn = req.getScmInventoryIn();
        scmInventoryIn.setTenantId(sysUser.getTenantId());
        scmInventoryIn.setCreateTime(System.currentTimeMillis());
        scmInventoryIn.setCreateUser(String.valueOf(sysUser.getUserId()));
        scmInventoryIn.setStatus("pending");
        int i = scmInventoryInMapper.insertSelective(scmInventoryIn);

        List list = req.getScmInventoryInDetailList();
        if(!CollectionUtils.isEmpty(list)){
            for (ScmInventoryInDetail scmInventoryInDetail : req.getScmInventoryInDetailList()) {
                scmInventoryInDetail.setTenantId(sysUser.getTenantId());
                scmInventoryInDetail.setInventoryInId(scmInventoryIn.getId());
                scmInventoryInDetail.setCreateTime(System.currentTimeMillis());
                scmInventoryInDetail.setCreateUser(String.valueOf(sysUser.getUserId()));
            }

            scmInventoryInDetailMapper.batchInsert(list);
        }

        return 1;
    }

    @Override
    public int updateScmInventoryIn(SaveScmInventoryInReq req, SysUser sysUser) {

        ScmInventoryIn scmInventoryIn = req.getScmInventoryIn();
        scmInventoryIn.setTenantId(sysUser.getTenantId());
        scmInventoryIn.setUpdateTime(System.currentTimeMillis());
        scmInventoryIn.setUpdateUser(String.valueOf(sysUser.getUserId()));
        int i = scmInventoryInMapper.updateByPrimaryKeySelective(scmInventoryIn);

        ScmInventoryInDetailExample example = new ScmInventoryInDetailExample();
        example.createCriteria().andInventoryInIdEqualTo(scmInventoryIn.getId());
        scmInventoryInDetailMapper.deleteByExample(example);

        List list = req.getScmInventoryInDetailList();
        if(!CollectionUtils.isEmpty(list)){
            for (ScmInventoryInDetail scmInventoryInDetail : req.getScmInventoryInDetailList()) {
                scmInventoryInDetail.setTenantId(sysUser.getTenantId());
                scmInventoryInDetail.setInventoryInId(scmInventoryIn.getId());
                scmInventoryInDetail.setCreateTime(System.currentTimeMillis());
                scmInventoryInDetail.setCreateUser(String.valueOf(sysUser.getUserId()));
            }

            scmInventoryInDetailMapper.batchInsert(list);
        }

        return 0;
    }

    @Transactional
    @Override
    public synchronized int confirmScmInventoryIn(Long inventoryInId, SysUser sysUser) {

        //添加相关入库产品的库存信息，没有则新增，有则累加
        ScmInventoryInDetailExample example = new ScmInventoryInDetailExample();
        example.createCriteria().andInventoryInIdEqualTo(inventoryInId);
        List<ScmInventoryInDetail> detailList =  scmInventoryInDetailMapper.selectByExample(example);

        //入库
        if(CollectionUtils.isEmpty(detailList)){
            return 1;
        }

        for (ScmInventoryInDetail scmInventoryInDetail : detailList) {
            inventoryStashProductService.saveStashProduct(sysUser.getTenantId(),scmInventoryInDetail);
        }
        //todo 确认入库是否需要上传相关凭证
        //todo 操作记录跟踪
        ScmInventoryIn scmInventoryIn = scmInventoryInMapper.selectByPrimaryKey(inventoryInId);
        scmInventoryIn.setStatus("success");
        scmInventoryInMapper.updateByPrimaryKey(scmInventoryIn);

        return 1;
    }




}
